//route包函数封装
//route.go
package route

import (
	"fmt"
	"log"
	"net/http"
	"strings"
)

type MyMux struct {
	handlers map[string][]*Handler //用于存储http.HandleFunc("/", SayhelloName) 格式的路由规则
}

type Handler struct {
	path string
	http.HandlerFunc
}

//开启http服务
func (m *MyMux) Listen(port string) {
	err := http.ListenAndServe(port, m)
	if err != nil {
		log.Fatal("开启http服务错误!")
	}
}

func NewMyMux() *MyMux {
	return &MyMux{make(map[string][]*Handler)}
}

//添加路由
func (m *MyMux) AddRoute(mode string, path string, fun http.HandlerFunc) {
	m.add(mode, path, fun)
}

//添加路由
/*mode  Post|Get|Put|Delete
 *path  前缀
 *fun	方法
 */
func (m *MyMux) add(mode, path string, fun http.HandlerFunc) {
	h := &Handler{
		strings.ToLower(path),
		fun}

	//fmt调试代码可以删除
	fmt.Println("h ::", &h)
	fmt.Println("strings.ToLower(path) ::", strings.ToLower(path))
	fmt.Println("strings.ToLower(mode) ::", strings.ToLower(mode))

	//下面是存储路由的核心代码，这里的路由m.handlers存储的格式是Get|Post|Put|Delete:String:http.HandlerFunc
	m.handlers[strings.ToLower(mode)] = append(
		m.handlers[strings.ToLower(mode)],
		h,
	)
	fmt.Println("m.handlers", m.handlers[strings.ToLower(mode)])
}

//优化前代码
/*
func (p *MyMux) ServeHTTP2(w http.ResponseWriter, r *http.Request) {
	//下面是路由处理，一般web框架会使用一个封装函数统一处理
	if r.URL.Path == "/" {
		sayhelloName(w, r) //这是所有web框架路由的核心代码
		return
	}
	http.NotFound(w, r)
	return
}
*/

//进行路由分配

func (m *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//处理静态文件
	url := strings.Split(strings.TrimLeft(r.URL.Path, "/"), "/")

	//调试代码，可以直接删除
	fmt.Println("r", fmt.Sprintf("%+v", r))
	fmt.Println("w", fmt.Sprintf("%+v", w))

	for _, handler := range m.handlers[strings.ToLower(r.Method)] {
		if handler.path == "/"+strings.ToLower(url[0]) {
			handler.ServeHTTP(w, r) //调用的是func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) }
			return
		}
	}
	http.NotFound(w, r)
	return
}
